package cn.tedu.d20_reflection3;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/*
 反射缺点
   破环封装

   通过反射复制对象
 */
public class ReflectDemo01 {
    public static void main(String[] args) throws Exception {
        Foo01 f1=new Foo01(1,"寻悟空",500);
        System.out.println(f1);

        //通过反射创建对象 1,翠花,20
        //1.获取f1的字节码对象
        Class c=f1.getClass();
        //获取私有属性
        Field id = c.getDeclaredField("id");
        id.setAccessible(true);//可以访问私有属性，破坏封装
        int idValue = id.getInt(f1);
        Field name = c.getDeclaredField("name");
        name.setAccessible(true);
        String nameValue = (String) name.get(f1);
        Field age = c.getDeclaredField("age");
        age.setAccessible(true);
        int ageValue=age.getInt(f1);
//        c.newInstance();//调用无参构造
        //调用有参构造方法
        Constructor con = c.getConstructor(
                int.class, String.class, int.class);

        Foo01 f2 = (Foo01) con.newInstance(
                idValue, nameValue, ageValue);
        System.out.println("f2:"+f2);




    }
}
class Foo01{
    private int id;
    private String name;
    private  int age;

    public Foo01() {
    }

    public Foo01(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString(){
        return id+","+name+","+age;
    }
}